<template>
  <div class="notification-list-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>消息通知</h1>
        <div class="header-actions">
          <el-button 
            v-if="unreadCount > 0"
            type="primary" 
            link 
            @click="markAllAsRead"
            size="small"
          >
            全部已读
          </el-button>
        </div>
      </div>

      <!-- 筛选标签 -->
      <div class="filter-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部" name="all">
            <template #label>
              全部
              <el-badge :value="totalCount" :hidden="totalCount === 0" class="tab-badge" />
            </template>
          </el-tab-pane>
          <el-tab-pane label="未读" name="unread">
            <template #label>
              未读
              <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="tab-badge" />
            </template>
          </el-tab-pane>
          <el-tab-pane label="订单" name="order">
            <template #label>
              订单通知
            </template>
          </el-tab-pane>
          <el-tab-pane label="系统" name="system">
            <template #label>
              系统通知
            </template>
          </el-tab-pane>
          <el-tab-pane label="优惠" name="promotion">
            <template #label>
              优惠活动
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 通知列表 -->
      <div class="notification-list" v-loading="loading">
        <div 
          v-for="notification in filteredNotifications" 
          :key="notification.id"
          class="notification-item"
          :class="{ 
            'unread': !notification.isRead,
            'read': notification.isRead 
          }"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-icon">
            <el-icon :size="24" :color="getNotificationIconColor(notification.type)">
              <component :is="getNotificationIcon(notification.type)" />
            </el-icon>
          </div>
          
          <div class="notification-content">
            <div class="notification-header">
              <h4 class="notification-title">{{ notification.title }}</h4>
              <div class="notification-meta">
                <span class="notification-time">{{ formatTime(notification.createdAt) }}</span>
                <el-dropdown @command="handleNotificationAction">
                  <el-button type="primary" link size="small" @click.stop>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        :command="{ action: 'toggleRead', notification }"
                        :icon="notification.isRead ? 'View' : 'Hide'"
                      >
                        {{ notification.isRead ? '标记未读' : '标记已读' }}
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{ action: 'delete', notification }"
                        :icon="Delete"
                        class="delete-item"
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
            
            <p class="notification-description">{{ notification.content }}</p>
            
            <div class="notification-footer" v-if="notification.actionButton">
              <el-button 
                :type="notification.actionButton.type || 'primary'"
                size="small"
                @click.stop="handleActionButton(notification)"
              >
                {{ notification.actionButton.text }}
              </el-button>
            </div>
            
            <div class="notification-tags" v-if="notification.tags?.length">
              <el-tag 
                v-for="tag in notification.tags" 
                :key="tag"
                size="small"
                :type="getTagType(notification.type)"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty 
          v-if="!loading && filteredNotifications.length === 0"
          :description="getEmptyDescription()"
          class="empty-state"
        >
          <template #image>
            <el-icon :size="80" color="#d3d3d3">
              <Bell />
            </el-icon>
          </template>
          <el-button 
            v-if="activeTab === 'all'"
            type="primary" 
            @click="refreshNotifications"
          >
            刷新试试
          </el-button>
        </el-empty>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button 
          @click="loadMore"
          :loading="loadingMore"
          style="width: 100%;"
        >
          加载更多
        </el-button>
      </div>
    </div>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="currentNotification?.title"
      width="500px"
      @close="handleDialogClose"
    >
      <div class="notification-detail" v-if="currentNotification">
        <div class="detail-header">
          <div class="detail-icon">
            <el-icon :size="32" :color="getNotificationIconColor(currentNotification.type)">
              <component :is="getNotificationIcon(currentNotification.type)" />
            </el-icon>
          </div>
          <div class="detail-meta">
            <el-tag :type="getTagType(currentNotification.type)" size="small">
              {{ getTypeText(currentNotification.type) }}
            </el-tag>
            <span class="detail-time">{{ formatDateTime(currentNotification.createdAt) }}</span>
          </div>
        </div>
        
        <div class="detail-content">
          <p>{{ currentNotification.content }}</p>
          
          <div v-if="currentNotification.extraInfo" class="detail-extra">
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item 
                v-for="(value, key) in currentNotification.extraInfo"
                :key="key"
                :label="key"
              >
                {{ value }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button 
            v-if="currentNotification?.actionButton"
            :type="currentNotification.actionButton.type || 'primary'"
            @click="handleActionButton(currentNotification)"
          >
            {{ currentNotification.actionButton.text }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  MoreFilled,
  Delete,
  Bell,
  ChatDotRound,
  ShoppingCart,
  Setting,
  Gift,
  Warning,
  InfoFilled,
  SuccessFilled,
  View,
  Hide
} from '@element-plus/icons-vue'
import { notificationApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const loading = ref(true)
const loadingMore = ref(false)
const notifications = ref([])
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const showDetailDialog = ref(false)
const currentNotification = ref(null)

// 定时刷新
let refreshTimer = null

// 计算属性
const totalCount = computed(() => notifications.value.length)

const unreadCount = computed(() => 
  notifications.value.filter(n => !n.isRead).length
)

const filteredNotifications = computed(() => {
  let filtered = notifications.value
  
  switch (activeTab.value) {
    case 'unread':
      filtered = notifications.value.filter(n => !n.isRead)
      break
    case 'order':
      filtered = notifications.value.filter(n => n.type === 'order')
      break
    case 'system':
      filtered = notifications.value.filter(n => n.type === 'system')
      break
    case 'promotion':
      filtered = notifications.value.filter(n => n.type === 'promotion')
      break
    default:
      filtered = notifications.value
  }
  
  return filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
})

// 生命周期
onMounted(() => {
  fetchNotifications()
  
  // 设置定时刷新
  refreshTimer = setInterval(() => {
    refreshNotifications()
  }, 60000) // 每分钟刷新一次
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})

// 方法定义
const fetchNotifications = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      currentPage.value = 1
    } else {
      loadingMore.value = true
    }
    
    const response = await notificationApi.getNotifications({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    const newNotifications = response.data.notifications || []
    
    if (isLoadMore) {
      notifications.value.push(...newNotifications)
    } else {
      notifications.value = newNotifications
    }
    
    hasMore.value = newNotifications.length === pageSize.value
    
  } catch (error) {
    console.error('获取通知列表失败:', error)
    
    // 使用模拟数据
    const mockNotifications = [
      {
        id: 1,
        type: 'order',
        title: '订单状态更新',
        content: '您的订单 #202412280001 已开始服务，预计30分钟内完成。',
        isRead: false,
        createdAt: new Date(Date.now() - 300000),
        actionButton: {
          text: '查看订单',
          type: 'primary',
          action: 'viewOrder',
          params: { orderId: 1 }
        },
        tags: ['服务中'],
        extraInfo: {
          '订单号': '#202412280001',
          '服务项目': '高档衣物干洗',
          '预计完成': '15:30'
        }
      },
      {
        id: 2,
        type: 'promotion',
        title: '限时优惠活动',
        content: '新用户专享8折优惠券已到账，有效期7天，快来体验我们的专业服务！',
        isRead: false,
        createdAt: new Date(Date.now() - 3600000),
        actionButton: {
          text: '立即使用',
          type: 'success',
          action: 'useCoupon'
        },
        tags: ['优惠券', '限时']
      },
      {
        id: 3,
        type: 'system',
        title: '服务评价提醒',
        content: '您的订单已完成，请为本次服务进行评价，您的反馈对我们很重要。',
        isRead: true,
        createdAt: new Date(Date.now() - 7200000),
        actionButton: {
          text: '去评价',
          type: 'primary',
          action: 'rateOrder',
          params: { orderId: 2 }
        },
        tags: ['评价']
      },
      {
        id: 4,
        type: 'order',
        title: '订单支付成功',
        content: '订单 #202412280002 支付成功，商家将尽快为您安排服务。',
        isRead: true,
        createdAt: new Date(Date.now() - 86400000),
        extraInfo: {
          '订单号': '#202412280002',
          '支付金额': '¥65.00',
          '支付方式': '微信支付'
        }
      },
      {
        id: 5,
        type: 'system',
        title: '账户安全提醒',
        content: '检测到您的账户在新设备上登录，如非本人操作请及时修改密码。',
        isRead: true,
        createdAt: new Date(Date.now() - 172800000),
        actionButton: {
          text: '查看详情',
          type: 'warning',
          action: 'viewSecurity'
        },
        tags: ['安全']
      }
    ]
    
    if (isLoadMore) {
      notifications.value.push(...mockNotifications.slice(0, 2))
    } else {
      notifications.value = mockNotifications
    }
    
    ElMessage.error('获取通知列表失败，显示模拟数据')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const refreshNotifications = async () => {
  try {
    const response = await notificationApi.getNotifications({
      page: 1,
      pageSize: pageSize.value
    })
    
    const newNotifications = response.data.notifications || []
    notifications.value = newNotifications
  } catch (error) {
    console.error('刷新通知失败:', error)
  }
}

const loadMore = () => {
  currentPage.value++
  fetchNotifications(true)
}

const handleBack = () => {
  router.back()
}

const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const handleNotificationClick = async (notification) => {
  // 标记为已读
  if (!notification.isRead) {
    await markAsRead(notification)
  }
  
  // 显示详情或执行默认操作
  if (notification.actionButton) {
    handleActionButton(notification)
  } else {
    currentNotification.value = notification
    showDetailDialog.value = true
  }
}

const handleNotificationAction = async ({ action, notification }) => {
  switch (action) {
    case 'toggleRead':
      if (notification.isRead) {
        await markAsUnread(notification)
      } else {
        await markAsRead(notification)
      }
      break
    case 'delete':
      await deleteNotification(notification)
      break
  }
}

const markAsRead = async (notification) => {
  try {
    await notificationApi.markAsRead(notification.id)
    notification.isRead = true
    ElMessage.success('已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    notification.isRead = true // 模拟成功
  }
}

const markAsUnread = async (notification) => {
  try {
    await notificationApi.markAsUnread(notification.id)
    notification.isRead = false
    ElMessage.success('已标记为未读')
  } catch (error) {
    console.error('标记未读失败:', error)
    notification.isRead = false // 模拟成功
  }
}

const markAllAsRead = async () => {
  try {
    await notificationApi.markAllAsRead()
    notifications.value.forEach(n => n.isRead = true)
    ElMessage.success('全部已标记为已读')
  } catch (error) {
    console.error('批量标记已读失败:', error)
    notifications.value.forEach(n => n.isRead = true) // 模拟成功
  }
}

const deleteNotification = async (notification) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条通知吗？删除后无法恢复。',
      '删除通知',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await notificationApi.deleteNotification(notification.id)
    
    const index = notifications.value.findIndex(n => n.id === notification.id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
    
    ElMessage.success('通知已删除')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleActionButton = (notification) => {
  const { action, params } = notification.actionButton
  
  switch (action) {
    case 'viewOrder':
      router.push(`/orders/${params.orderId}`)
      break
    case 'rateOrder':
      router.push(`/orders/${params.orderId}/rating`)
      break
    case 'useCoupon':
      router.push('/coupons')
      break
    case 'viewSecurity':
      router.push('/profile/security')
      break
    default:
      ElMessage.info('功能开发中')
  }
  
  showDetailDialog.value = false
}

const handleDialogClose = () => {
  currentNotification.value = null
}

const getNotificationIcon = (type) => {
  const iconMap = {
    order: ShoppingCart,
    system: Setting,
    promotion: Gift,
    warning: Warning,
    info: InfoFilled,
    success: SuccessFilled
  }
  return iconMap[type] || Bell
}

const getNotificationIconColor = (type) => {
  const colorMap = {
    order: '#409eff',
    system: '#909399',
    promotion: '#f56c6c',
    warning: '#e6a23c',
    info: '#409eff',
    success: '#67c23a'
  }
  return colorMap[type] || '#909399'
}

const getTagType = (notificationType) => {
  const typeMap = {
    order: 'primary',
    system: 'info',
    promotion: 'danger',
    warning: 'warning',
    success: 'success'
  }
  return typeMap[notificationType] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    order: '订单通知',
    system: '系统通知',
    promotion: '优惠活动',
    warning: '警告',
    info: '信息',
    success: '成功'
  }
  return textMap[type] || '通知'
}

const getEmptyDescription = () => {
  const descMap = {
    all: '暂无通知消息',
    unread: '暂无未读消息',
    order: '暂无订单通知',
    system: '暂无系统通知',
    promotion: '暂无优惠活动'
  }
  return descMap[activeTab.value] || '暂无消息'
}

const formatTime = (date) => {
  const now = dayjs()
  const time = dayjs(date)
  const diffDays = now.diff(time, 'day')
  
  if (diffDays === 0) {
    return time.format('HH:mm')
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return time.format('MM-DD')
  }
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.notification-list-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .header-actions {
    display: flex;
    align-items: center;
  }
}

.filter-tabs {
  background: white;
  border-radius: 12px;
  padding: 0 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  .tab-badge {
    margin-left: 4px;
  }
}

.notification-list {
  .notification-item {
    background: white;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    gap: 12px;
    position: relative;

    &:hover {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }

    &.unread {
      border-left: 4px solid #409eff;
      
      &::before {
        content: '';
        position: absolute;
        top: 16px;
        right: 16px;
        width: 8px;
        height: 8px;
        background: #f56c6c;
        border-radius: 50%;
      }
    }

    .notification-icon {
      flex-shrink: 0;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .notification-content {
      flex: 1;
      min-width: 0;

      .notification-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 8px;

        .notification-title {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
          flex: 1;
          line-height: 1.4;
        }

        .notification-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-shrink: 0;

          .notification-time {
            color: #999;
            font-size: 12px;
          }
        }
      }

      .notification-description {
        margin: 0 0 12px 0;
        color: #666;
        font-size: 14px;
        line-height: 1.5;
      }

      .notification-footer {
        margin-bottom: 8px;
      }

      .notification-tags {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
      }
    }
  }
}

.load-more {
  margin-top: 20px;
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 40px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.notification-detail {
  .detail-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .detail-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .detail-meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8px;

      .detail-time {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .detail-content {
    p {
      margin: 0 0 16px 0;
      color: #666;
      line-height: 1.6;
    }

    .detail-extra {
      margin-top: 16px;
    }
  }
}

:deep(.delete-item) {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .notification-item {
    padding: 12px;

    .notification-content {
      .notification-header {
        flex-direction: column;
        gap: 8px;

        .notification-meta {
          align-self: flex-start;
        }
      }
    }
  }

  .filter-tabs {
    padding: 0 10px;

    :deep(.el-tabs__item) {
      font-size: 14px;
      padding: 0 10px;
    }
  }
}
</style> 